package br.com.wepa.webapps.orca.controle.actions.login;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import br.com.wepa.webapps.logger.TraceLogger;
import br.com.wepa.webapps.orca.controle.ControleWeb;
import br.com.wepa.webapps.orca.controle.actions.struts.SuperAction;
import br.com.wepa.webapps.orca.logica.modelo.Usuario;
import br.com.wepa.webapps.orca.logica.negocio.facade.FacadeDelegator;
import br.com.wepa.webapps.orca.logica.negocio.facade.LoginFacadeHome;
import br.com.wepa.webapps.orca.logica.negocio.facade.to.LoginTO;

public class LoginAction extends SuperAction {
	/**
	 * Objeto de Log
	 */
	private static final TraceLogger logger = new TraceLogger(LoginAction.class);

	public static final String ERRO_LOGIN_INVALIDO = "user.error.loginPassword.invalid";

	public static final String FORWARD_LOGIN_PAGE = "loginPage";

	public LoginAction() {
	}

	public ActionForward login(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		logger.entering();
		request.getSession().invalidate();
		request.getSession(true);
		LoginFacadeHome facade = FacadeDelegator.getLoginFacade();

		LoginTO to = facade.instanceTO();
		super.copyFormToObject(to, form);
		Usuario usuario = facade.login(to);

		if (usuario == null) {
			super.addError(request, ERRO_LOGIN_INVALIDO);
			return mapping.findForward(FORWARD_LOGIN_PAGE);
		}

		ControleWeb.doAuthentication(request, new Autenticacao(usuario));

		UsuarioSessao usuarioWeb = new UsuarioSessao();
		usuarioWeb.fill(usuario);
		request.getSession().setAttribute(USUARIOWEB, usuarioWeb);

		logger.exiting();
		return mapping.findForward(GLOBAL_FWPAGE_PRINCIPAL);
	}
		
	
	public ActionForward sessaoExpirada(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		logger.entering();
		super.addError(request, ERROR_SESSAO_EXPIRADA);
		logger.exiting();
		return mapping.findForward(FORWARD_LOGIN_PAGE);
	}

	@Override
	protected String getForwardErroName(String nomeMetodo) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected ActionForward principal(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		return mapping.findForward(FORWARD_LOGIN_PAGE);
	}

}